//
//  RefreshView.swift
//  Jock
//
//  Created by HD on 15/3/20.
//  Copyright (c) 2015年 Haidy. All rights reserved.
//

import UIKit

var Context = ""
let contentOffsetKeyPath = "contentOffset"

protocol RefreshViewDelegate {
    func pushToRefresh()
    
    func releaseToRefresh()
    
    func pushOffset(offset: CGFloat)
    
    func refresh()
}

enum RefreshStatus: Int {
    
    case Nornal = 0 //正常
    case Push = 1   //下拉
    case Release = 2//释放
    case Refresh = 3//刷新
    
}

class RefreshView: UIView {

    private var scrollViewBouncesDefaultValue: Bool = false
    private var scrollViewInsetsDefaultValue: UIEdgeInsets = UIEdgeInsetsZero
    
    private var previousOffset: CGFloat = 0
    
    var delegate: RefreshViewDelegate?
    var refreshTriggerHeight: CGFloat = 60
    var refreshNormalHeight: CGFloat = 0
    
    var loading: Bool = false
    var refreshStatus = RefreshStatus.Nornal
    
    override init(frame: CGRect) {
        super.init(frame: frame)
    }

    required init(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }
    
    override func willMoveToSuperview(newSuperview: UIView!) {
        superview?.removeObserver(self, forKeyPath: contentOffsetKeyPath, context: &Context)
        if (newSuperview != nil && newSuperview.isKindOfClass(UIScrollView)) {
            newSuperview.addObserver(self, forKeyPath: contentOffsetKeyPath, options: .Initial, context: &Context)
            scrollViewBouncesDefaultValue = (newSuperview as! UIScrollView).bounces
            scrollViewInsetsDefaultValue = (newSuperview as! UIScrollView).contentInset
        }
    }
    
    override func observeValueForKeyPath(keyPath: String, ofObject object: AnyObject, change: [NSObject : AnyObject], context: UnsafeMutablePointer<Void>) {
        if (context == &Context) {
            var scrollView = superview as? UIScrollView
            if (keyPath == contentOffsetKeyPath && object as? UIScrollView == scrollView) {
                var scrollView = object as? UIScrollView
                if (scrollView != nil && delegate != nil) {
                    let offset = scrollView!.contentOffset.y
                    if offset < refreshNormalHeight {
                        if offset > refreshNormalHeight - refreshTriggerHeight {//触发刷新之前
                            if refreshStatus == RefreshStatus.Nornal {
                                refreshStatus = RefreshStatus.Push
                                delegate?.pushToRefresh()
                            } else if refreshStatus == RefreshStatus.Release  {
                                if scrollView?.dragging == false {
                                    refreshStatus = RefreshStatus.Refresh
                                    delegate?.refresh()
                                    startAnim()
                                } else {
                                    refreshStatus = RefreshStatus.Push
                                    delegate?.pushToRefresh()
                                }
                            }
                        } else {
                            if refreshStatus == RefreshStatus.Push {
                                refreshStatus = RefreshStatus.Release
                                delegate?.releaseToRefresh()
                            } else if refreshStatus == RefreshStatus.Release && !scrollView!.dragging && previousOffset - offset < 0 {
                                refreshStatus = RefreshStatus.Refresh
                                delegate?.refresh()
                                startAnim()
                            }
                        }
                    }
                    previousOffset = offset
                    delegate?.pushOffset(previousOffset)
                }
            }
        } else {
            super.observeValueForKeyPath(keyPath, ofObject: object, change: change, context: context)
        }
    }
    
    func startRefresh() {
        startAnim()
        if delegate != nil {
            delegate?.refresh()
        }
    }
    
    // 开始动画
    private func startAnim() {
        var scrollView = superview as! UIScrollView
        var insets = scrollView.contentInset
        insets.top += self.frame.size.height
        UIView.animateWithDuration(0.2, animations: { () -> Void in
            scrollView.contentInset = insets
        })
    }
    
    // 结束刷新
    func endRefresh() {
        stopAnim()
    }
    
    // 结束动画
    private func stopAnim() {
        var scrollView = superview as! UIScrollView
        var insets = scrollView.contentInset
        insets.top = 64
        UIView.animateWithDuration(0.3, animations: { () -> Void in
            if self.refreshNormalHeight == 0 {
                scrollView.contentInset = self.scrollViewInsetsDefaultValue
            } else {
                scrollView.contentInset = insets//self.scrollViewInsetsDefaultValue
            }
            }) { (Bool) -> Void in
                self.refreshStatus = RefreshStatus.Nornal
        }
    }

}
